/**
 * Created by 77element-01 on 2016/3/16.
 */
/*右击选中的对象*/
var contextMenuobj;
/*右击选中的对象的属性*/
var contextMenuType;
/*右击选中的对象的属性*/
var contextMenuobjEven;
/*右击线条的属性*/
var connectorEven;
/*把所有生成的echart存在数组里*/
var $echart = [];
/*临时ehcart图*/
var option = {
    title  : {
        text: '柱状图'
    },
    tooltip: {
        trigger: 'item'
    },
    legend : {
        data   : ['echart'],
        itemGap: 5
    },
    grid   : {
        top         : '30px',
        left        : '3%',
        right       : '4%',
        bottom      : '3%',
        containLabel: true
    },
    toolbox: {
        feature: {
            mark       : {show: true},
            magicType  : {show: true, type: ['line', 'bar']},
            restore    : {show: true},
            saveAsImage: {show: true}
        }
    },
    xAxis  : {
        type       : 'category',
        boundaryGap: false,
        data       : ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis  : {
        type: 'value'
    },
    series : [
        {
            name : 'echart',
            type : 'bar',
            stack: '总量',
            data : [10, 132, 50, 34, 90, 230, 30]
        }
    ]
};
var option1 = {
    title  : {
        text   : '饼图',
        subtext: '纯属虚构',
        x      : 'center'
    },
    tooltip: {
        trigger  : 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend : {
        orient: 'vertical',
        left  : 'left',
        data  : ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
    },
    series : [
        {
            name     : '访问来源',
            type     : 'pie',
            radius   : '55%',
            center   : ['50%', '60%'],
            data     : [
                {value: 335, name: '直接访问'},
                {value: 310, name: '邮件营销'},
                {value: 234, name: '联盟广告'},
                {value: 135, name: '视频广告'},
                {value: 1548, name: '搜索引擎'}
            ],
            itemStyle: {
                emphasis: {
                    shadowBlur   : 10,
                    shadowOffsetX: 0,
                    shadowColor  : 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
};
var option2 = {
    tooltip: {
        formatter: "{a} <br/>{b} : {c}%"
    },
    toolbox: {
        feature: {
            restore    : {},
            saveAsImage: {}
        }
    },
    series : [
        {
            name  : '业务指标',
            type  : 'gauge',
            detail: {formatter: '{value}%'},
            data  : [{value: 50, name: '完成率'}]
        }
    ]
};
/**
 * 右击弹出层
 * @param id 新建组件或线条的id
 * @param e  新建组件的属性
 */
function showContextMenu(id, e) {

    var type, orderMenu;
    orderMenu = $("#_context");
    type = 'getAttribute' in id ? 'order' : 'connector';
    orderMenu.css({left: e.pageX + "px", top: e.pageY + "px"}).show()
        .find('.menu').hide().end()
        .find('.' + type).show();
}
/**
 * 容器处理
 * @param canvas 区域
 * @private
 */
function _container(canvas) {
    $('#canvas .container .condrog').droppable({
        accept: ":not(.ui-sortable-helper)",
        drop  : function (event, u) {
            u.draggable.css("left", '').css("top", '');
            u.draggable.appendTo(this);
            u.draggable.draggable("disable");
            u.draggable.resizable({
                containment: '#canvas .container'
            });
            $(this).height('auto');
            $(this).width('auto');
        }
    }).sortable({
        connectWith: '#canvas',
        sort       : function (e, u) {
            // 获取由 droppable 与 sortable 交互而加入的条目
            // 使用 connectWithSortable 可以解决这个问题，但不允许您自定义 active/hoverClass 选项
            $(this).removeClass("ui-state-default");
            instance.repaintEverything();
        },
        remove     : function (e, u) {
            var left = parseInt(u.offset.left - canvas.offset().left + canvas.scrollLeft());
            var top = parseInt(u.offset.top - canvas.offset().top + canvas.scrollTop());
            u.item.css("left", left).css("top", top);
            u.item.draggable('enable');
            u.item.resizable({
                containment: '#canvas'
            });
        },
        stop       : function () {
            instance.repaintEverything();
        }
    });
}
/**
 * 创建组件的id用
 * @type {number}
 */
var i = 0;
/**
 * 拖动创建组件
 * @param e 被复制的元素
 * @param ui 被复制的元素的属性
 */
function CreateModel(e, ui) {
    //1.1 添加html模型
    var canvas  = $('#canvas'),
        type    = ui.helper.attr('type') ? ui.helper.attr('type') : '',
        modelid = $(ui.draggable).attr("id");

    i++;
    var id   = modelid + i,
        html = '<div class="window" id="' + id + '" type="' + type + '">' + $(ui.helper).html() + '</div>',
        html = type.indexOf('echart') >= 0 ? '<div class="window" id="' + id + '" type="' + type + '"><div class="w-content" id="echart-' + i + '" ></div></div>' : html,
        html = type == 'container' ? '<div class="container" type="' + type + '" id="' + id + '">' + $(ui.helper).html() + '</div>' : html;
    canvas.append(html);
    var left = parseInt(ui.offset.left - canvas.offset().left + canvas.scrollLeft()),
        top  = parseInt(ui.offset.top - canvas.offset().top + canvas.scrollTop());
    $("#" + id).css({
        "left": left,
        "top" : top
    });

    //jsPlumb.setContainer($("#divCenter"));
    //1.2 添加连接点
    __jsplumb(id);
    //1.3 注册实体可draggable和resizable
    $("#" + id).draggable({
        appendTo: "#canvas",
        scroll  : true,
        grid    : [10, 10],
        heiper  : 'clone',
        drag    : function (event, ui) {
            //MoveSelectDiv(event, ui, id);
            instance.repaintEverything();
        },
        stop    : function () {
            instance.repaintEverything();
        }
    })

    $("#" + id).resizable({
        autoHide: true,//当用户鼠标没有悬浮在元素上时是否隐藏手柄
        grid    : [5, 5],//把可调整尺寸元素对齐到网格，每个 x 和 y 像素
        resize  : function (e, u) {

            /*属性为容器*/
            if (type == 'container') {
                var ow    = u.originalSize.width,
                    hw    = u.helper.width(),
                    oh    = u.originalSize.height,
                    hh    = u.helper.height(),
                    $this = u.element;
                $(this).find('.condrog').css({
                    'height': "100%",
                    'width' : "100%"
                });
                if (oh == hh) {
                    $this.height("auto");
                    $this.find('.condrog').height('auto');
                } else if (ow == hw) {
                    $this.width('auto');
                    $this.find('.condrog').width("auto");
                }
            }
            /*属性为任意echart*/
            if (type.indexOf('echart') >= 0) {
                var n = $(this).find('.w-content').attr('id');
                var $id = n.charAt(n.length - 1, 1);
                $echart[$id].resize();
            }
            /*属性为table*/
            type == 'table' ? $("div[id^='tableContent']").perfectScrollbar('update') : '';
            instance.repaintEverything();
        }
    });
    /*属性为容器*/
    if (type == 'container') {
        _container(canvas);
    }
    /*属性为柱状图*/
    if (type == 'echart-bar') {
        $echart[i] = echarts.init($("#echart-" + i)[0]);
        $echart[i].setOption(option);
    }
    /*属性为饼图*/
    if (type == 'echart-pie') {
        $echart[i] = echarts.init($("#echart-" + i)[0]);
        $echart[i].setOption(option1);
    }
    /*属性为仪表盘*/
    if (type == 'echart-gauge') {
        $echart[i] = echarts.init($("#echart-" + i)[0]);
        $echart[i].setOption(option2);
    }
    /*属性为table*/
    if (type == 'table') {
        $("#" + id).find('.tableContent').attr('id', 'tableContent' + i);
        /*滚动条条用*/
        $("div[id^='tableContent']").perfectScrollbar({suppressScrollX: true, wheelSpeed: .5});
    }
    /*设置组件右击事件*/
    $('#' + id).contextmenu(function (e) {
        allHide();
        contextMenuobj = this;
        contextMenuType = $(this).attr('type');
        contextMenuobjEven = e;
        showContextMenu(this, e);
        e.stopPropagation();
        return false;
    })
};

$(function () {
    /* 右击-关闭：隐藏所有右击弹出层*/
    $('._close').click(function () {
        allHide();
    })
    /*右击-删除：删除一个节点以及连接的线条*/
    $('._delete').click(function () {
        instance.remove(contextMenuobj);
        allHide();
    })
    /**
     * $n   echart图的id
     * $id  截取当前echart图id最后的数值
     */
    var $n, $id;
    /*非线条对应属性的编辑弹出层*/
    $(".order._edit").click(function (e) {
        allHide();
        if (contextMenuType.indexOf('echart') >= 0) {
            contextMenuType = 'echart';
            $n = $(contextMenuobj).find('.w-content').attr('id');
            $id = $n.charAt($n.length - 1, 1);
        }
        $("#"+contextMenuType+'_edit').css({
            left: contextMenuobjEven.pageX + "px",
            top : contextMenuobjEven.pageY + "px"
        }).show().draggable();
        e.stopPropagation();
        e.preventDefault();
    })

    /*echart确认键提交数据处理*/
    $('#echart_edit .submit').click(function () {
        var n = $('#echartValue').val();
        console.log(contextMenuType);
        allHide();
    })
    /*table确认键提交数据处理*/
    $('#table_edit .submit').click(function () {
        var n = $('#tableValue').val();
        console.log(contextMenuType);
        console.log(n);
        allHide();
    })
    /*截图*/
    $('.screenshots').click(function () {
        html2canvas($('body'),
            {
                onrendered: function (canvas) {
                    $('#theface').attr('href', canvas.toDataURL());
                    $('#theface').attr('download', 'myjobdeer.png');
                    $('#theface').css('display', 'inline-block');

                }
            });
    })
})

jsPlumb.ready(function () {
    var canvasMenu = $('#canvas_context');
    //iniPlumb();
    //instance.setSuspendDrawing(false, true);
    // suspend drawing and initialise.暂停画画和初始化。
    iniPlumb();
    //instance.batch(function () {

    //弹出连接线的右键菜单
    instance.bind("contextmenu", function (connector, originalEvent) {
        lastConnector = connector;
        connectorEven = originalEvent;
        showContextMenu(connector, originalEvent);
        canvasMenu.hide();
        originalEvent.stopPropagation();
        originalEvent.preventDefault();
        return false;
    });
    /*线条编辑框弹出层*/
    $(".connector._edit").click(function (e) {
        allHide();
        var type = 'connector';
        $('#' + type + '_edit').css({
            left: connectorEven.pageX + "px",
            top : connectorEven.pageY + "px"
        }).show().draggable();
        e.stopPropagation();
        e.preventDefault();
    })
    //绑定到连接/ connectionDetached事件,和更新连接的列表在屏幕上。
    instance.bind("connection", function (info, originalEvent) {
        //updateConnections(info.connection);
    });
    instance.bind("connectionDetached", function (info, originalEvent) {
        //updateConnections(info.connection, true);
    });

    instance.bind("connectionMoved", function (info, originalEvent) {
        //只有删除,因为一个“连接”事件也解雇了
        //在以后版本的jsplumb这个额外的连接事件不会被解雇。
        //updateConnections(info.connection, true);
    });

    instance.bind("click", function (component, originalEvent) {
        //alert('click');
    });
    //删除一条连接线
    $(".connector._delete").click(function () {
        instance.detach(lastConnector);
        allHide();
    });
    //改变一条连接线为直线
    $("._straight").click(function (e) {
        e.preventDefault();
        changeConnectorType(["Straight"]);
    });
    //改变一条连接线为折线
    $("._flowchart").click(function (e) {
        e.preventDefault();
        changeConnectorType(["Flowchart", {
            stub              : [30, 30],
            gap               : 0,
            cornerRadius      : 5,
            alwaysRespectStubs: true
        }]);
    });
    //改变一条连接线为曲线
    $("._bezier").click(function (e) {
        e.preventDefault();
        changeConnectorType(["Bezier"]);
    });
    /*编辑线条*/
    $('.connector._edit').click(function (e) {

    })

    $('.left .window,.left .container').draggable({
        scope : 'plant',
        scroll: false,
        grid  : [10, 10],
        helper: "clone"
    })

    $('#canvas').droppable({
        scope: 'plant',
        drop : function (e, ui) {
            CreateModel(e, ui);
        }
    }).sortable({
        connectWith: '#canvas',

    })
    //    .selectable({
    //    start: function () {
    //        allHide();
    //    }
    //});
    //});


    //console.log(jsPlumb);
    //jsPlumb.fire("jsPlumbDemoLoaded", instance);

});
